<?php
/**
 * @authors alex (20779512@qq.com)
 * @date    2014-03-26 15:27:01
 * @version 1.0
 */

class BaseAction extends Action {
    
    public function _initialize(){

        $THEME_PATH = '/tpl/'.GROUP_NAME.'/';
        define('RES', $THEME_PATH . 'common');
        define('STATICS', '/tpl/' . 'static');

    }

    //获得access_token
    public function get_access_token(){
        $obj = M('AccessToken');
        $list = $obj->find();
        if ($list) {
            if (time() > $list['expire_in'] + 5000) {
                return $this->save_access_token('update');
            }else{
                return $list['access_token'];
            }
        }else{
            return $this->save_access_token('save');
        }
    }

    public function save_access_token($action){
        $obj = M('AccessToken');
        $access_token = $this->return_access_token();
        $data['access_token'] = $access_token;
        $data['expire_in'] = time();
        if ($action=='save') {
            $obj->add($data);
        }else{
            $obj->where('id=1')->save($data);
        }        
        return $access_token;
    }

    //获得access_token
    public function return_access_token(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C('APP_ID').'&secret='.C('APP_SECRET');
        $con = file_get_contents($url);
        $con = json_decode($con);
        return $con->access_token;
    }

    //获得jsTicket
    public function get_jsapi_ticket(){
        $obj = M('JsTicket');
        $list = $obj->find();
        if ($list) {
            if (time() > $list['expire_in'] + 3600) {
                return $this->save_js_ticket('update');
            }else{
                return $list['jsapi_ticket'];
            }
        }else{
            return $this->save_js_ticket('save');
        }        
    }

    //保存jsTicket
    public function save_js_ticket($action){
        $obj = M('JsTicket');
        $jsapi_ticket = $this->return_jsapi_ticket();
        $data['jsapi_ticket'] = $jsapi_ticket;
        $data['expire_in'] = time();
        if ($action=='save') {
            $obj->add($data);
        }else{
            $obj->where('id=1')->save($data);
        }        
        return $jsapi_ticket;
    }

    //从微信服务器拿到jsapi_ticket
    public function return_jsapi_ticket(){
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
        $con = file_get_contents($url);
        $con = json_decode($con);
        $jsapi_ticket = $con->ticket;
        return $jsapi_ticket;
    }

    //返回json数据
    public function echo_json_str($state , $message , $url=''){
		/*
		state 返回状态
		message 返回信息
		url 成功后跳转的页面
		*/
		if(empty($url)){
			$url = '';	
		}
		$josn_arr = array(
                        'state' =>   $state,
                        'message' => $message,
                        'url' => $url,
                        ); 

        return json_encode($josn_arr);

	}
	
	//验证码显示
	public function verify() {
		import("ORG.Util.Image");
		Image :: buildImageVerify();
	}

    #ajax传递过程中中文编码问题
    function phpUnescape($escstr) {
        preg_match_all("/%u[0-9A-Za-z]{4}|%.{2}|[0-9a-zA-Z.+-_]+/", $escstr, $matches);
        $ar = & $matches[0];
        $c = "";
        foreach ($ar as $val) {
            if (substr($val, 0, 1) != "%") { //如果是字母数字+-_.的ascii码
                $c .= $val;
            }
            elseif (substr($val, 1, 1) != "u") { //如果是非字母数字+-_.的ascii码
                $x = hexdec(substr($val, 1, 2));
                $c .= chr($x);
            } else { //如果是大于0xFF的码
                $val = intval(substr($val, 2), 16);
                if ($val < 0x7F) { //   0000-007F
                    $c .= chr($val);
                }
                elseif ($val < 0x800) { // 0080-0800
                    $c .= chr(0xC0 | ($val / 64));
                    $c .= chr(0x80 | ($val % 64));
                } else { // 0800-FFFF
                    $c .= chr(0xE0 | (($val / 64) / 64));
                    $c .= chr(0x80 | (($val / 64) % 64));
                    $c .= chr(0x80 | ($val % 64));
                }
            }
        }
        return $c;
    }

	//公用插入数据
	protected function all_add($name = '', $back = '/index'){
        $name = $name ? $name : MODULE_NAME;
        $obj = D($name);
        if ($data = $obj->create()) {
            if ($list = $obj->add($data)) {
                $state = 'SUCCESS';
                $message = '操作成功';
                $url = $back;
            } else {
                $state = '操作失败';
            }
        } else {
            $state = $obj->getError();
        }
        echo $this->echo_json_str($state,$message,$url); 
    }

    //公用更新数据
    protected function all_save($name = '', $back = '/index'){        
        $name = $name ? $name : MODULE_NAME;
        $obj = D($name);
        if ($data = $obj->create()) {
            if ($list = $obj->save($data)) {                
                $state = 'SUCCESS';
                $message = '操作成功';
                $url = $back;
            } else {
                $state = '操作失败';
            }            
        } else {
            $state = $obj->getError();
        }
        echo $this->echo_json_str($state,$message,$url); 
    }

     //邮件类
    public function think_send_mail($email, $name, $title, $content) {
        vendor('PHPMailer.class#phpmailer');
        $mail = new PHPMailer(); //实例化
        $mail->IsSMTP(); // 启用SMTP
        $mail->SMTPDebug = 0; // 关闭SMTP调试功能
        $mail->Host = C('SMTP_HOST'); //smtp服务器的名称
        $mail->SMTPAuth = true; //启用smtp认证
        $mail->Username = C('SMTP_USER'); //你的邮箱名
        $mail->Password = C('SMTP_PASS'); //邮箱密码
        $mail->From = C('FROM_EMAIL'); //发件人地址（也就是你的邮箱地址）
        $mail->FromName = C('FROM_NAME'); //发件人姓名
        $mail->AddAddress($email, $name); //添加收件人
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(true); // 是否HTML格式邮件
        $mail->CharSet = "utf-8"; //设置邮件编码
        $mail->Subject = $title; //主题
        $mail->Body = $content; //内容
        $mail->AltBody = ""; //正文不支持HTML的备用显示
        return $mail->Send();
    }


    //发送短信验证码
    public function send_mobile_sms($mobile,$content){

        import("@.ORG.Snoopy");

        $smsapi = C('SMS_API'); //短信网关 
        $user = C('SMS_USER'); //短信平台帐号 
        $pass = md5(C('SMS_PASSWORD')); //短信平台密码 
        $phone = $mobile;

        $snoopy = new snoopy();
        $sendurl = "http://{$smsapi}/sms?u={$user}&p={$pass}&m={$phone}&c=".urlencode($content);
        $snoopy->fetch($sendurl);
        $result = $snoopy->results;

        return $result;
    }

    #生成随机数
    public function GetRandStr($len){ 
        $chars = array( "0" , "1", "2", "3", "4", "5", "6", "7", "8", "9"); 
        $charsLen = count($chars) - 1; 
        shuffle($chars);   
        $output = ""; 
        for ($i=0; $i<$len; $i++){ 
            $output .= $chars[mt_rand(0, $charsLen)]; 
        }  
        return $output;  
    } 

    public function getUserType($v){
        foreach (C('USER_TYPE') as $key => $value) {
            if ($value['id']==$v) {
                return $value['name'];
            }
        }
    }


    //保存佣金记录
    public function saveYongjin($fromID , $childID , $totalMoney, $level=1){

        //超过级别退出程序
        if ($level>C('level_num')) {
            return;
        }

        $map['wxid'] = $childID;

        $fid = M('Member')->where($map)->getField('fid');
        if ($fid) {
            $where['wxid']=$fid;
            $father = M('Member')->where($where)->find();
            //上级是否必须消费后才能成为东家
            if (C('must_buy')==1) {                
                //判定上级是否是东家userGroup字段                
                if ($father['userGroup']==1 || $father['userType']==2 || $father['userType']==1) {
                    //保存佣金
                    //$money = $totalMoney * (C('level_'.$level)/100);
                    $money = C('level_'.$level);
                    $data['toUserID'] = $father['id'];                     
                    $data['toUserWx'] = $father['wxid']; 
                    //$data['fromUserID'] = $fromID;  
                    $data['fromUserWx'] = $fromID; 
                    $data['money'] = $money;
                    $data['totalMoney'] = $totalMoney;
                    $data['level'] = $level;
                    $data['createTime'] = time();
                    M('Yongjin')->add($data);

                    //设置用户表可用佣金
                    unset($map);
                    $map['wxid'] = $fid;
                    M('Member')->where($map)->setInc('money',$money);
                }
            }else{
                //保存佣金
                //$money = $totalMoney * (C('level_'.$level)/100);
                $money = C('level_'.$level);
                $data['toUserID'] = $father['id'];                     
                $data['toUserWx'] = $father['wxid']; 
                //$data['fromUserID'] = $fromID;  
                $data['fromUserWx'] = $fromID; 
                $data['money'] = $money;
                $data['totalMoney'] = $totalMoney;
                $data['level'] = $level;
                $data['createTime'] = time();
                M('Yongjin')->add($data);

                //设置用户表可用佣金
                unset($map);
                $map['wxid'] = $fid;
                M('Member')->where($map)->setInc('money',$money); 
            }
            $this->saveYongjin($fromID , $fid , $totalMoney , $level+1);
        }
    }


    public function logResult($word='') {
        $fp = fopen("log.txt","a");
        flock($fp, LOCK_EX) ;
        fwrite($fp,"执行日期：".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }

    public function https_post($url,$data = null){
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        if (!$empty) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);       
        return $output;
    }
}